<?php

namespace App\Http\Controllers\Admin\SystemSet\BlackList;

use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;    //引用http请求类
use App\Response\Response;

class BlackListRuleController extends BaseController {

    /**
     * @api {post} /system-set/black-list/rule 黑名单规则创建
     * @apiVersion 0.1.0
     * @apiName 系统设置-黑名单规则创建
     * @apiGroup 系统设置
     *
     * @apiParam {string} province_id                 省份id 必传
     * @apiParam {number} city_id                     城市id 必传
     * @apiParam {number} type                        受限类型 必传   0 全部   1 ip受限   2 归属地受限
     * @apiParam {array}  cate_ids                    黑名单类别 必传
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function create(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'province_id' => 'required|numeric|integer|exists:mysql.ln_district,district_id',
                'city_id' => 'required|numeric|integer|exists:mysql.ln_district,district_id',
                'type' => 'required|numeric|in:0,1,2',
                'cate_ids' => 'required|array',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $params = $request->input();

        $res = app('repo_black_list');

        $data = $res->getRule(["city_id" => $params['city_id']]);
        if($data){
            // 已存在该城市规则的情况下 分别判断
            if( (int)$data['type'] === 0 ){
                throw new BasicException(10001, '该城市已全部受限 不要重复添加!');
            }

            if( (int)$data['type'] === 1 && (int)$params['type'] === 1  ){
                throw new BasicException(10001, '该城市ip已受限！');
            }

            if(  (int)$data['type'] === 2 && (int)$params['type'] === 2  ){
                throw new BasicException(10001, '该城市已纳入归属地受限！');
            }
        }


        $city = app('repo_area')->getDistrict($params['city_id']);
        $province = app('repo_area')->getDistrict($params['province_id']);

        $cateIdsArr = $params['cate_ids'];

        $params['cate_ids'] = implode(",", $cateIdsArr);
        $params['area_name'] = $province['name'] . "-" . $city['name'];
        $params['add_time'] = time();
        $params['add_date_time'] = date("Y-m-d H:i:s");

        $rows = $res->addRule($params);
        if (!$rows) {
            throw new BasicException(10001, "插入失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {delete} /system-set/black-list/rule 黑名单规则删除
     * @apiVersion 0.1.0
     * @apiName 系统设置-黑名单规则删除
     * @apiGroup 系统设置
     *
     * @apiParam {string} ids                       字符串分割的id 必传
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function del(Request $request) {
        //参数校验
        try {
            $this->validate($request, [
                'ids' => 'required|string',
            ]);

        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $idsStr = $request->input("ids");
        $idsArr = explode("," , $idsStr);

        $rows = app('repo_black_list')->delRule($idsArr);
        if (!$rows) {
            throw new BasicException(10001, "删除失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {put} /system-set/black-list/rule 黑名单规则修改
     * @apiVersion 0.1.0
     * @apiName 系统设置-黑名单规则修改
     * @apiGroup 系统设置
     *
     *
     * @apiParam {string} province_id                 省份id 必传
     * @apiParam {number} city_id                     城市id 必传
     * @apiParam {number} type                        受限类型 必传   0 全部   1 ip受限   2 归属地受限
     * @apiParam {array}  cate_ids                    黑名单类别 必传
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function update(Request $request) {
        //参数校验
        try {
            $this->validate($request, [
                'id' => 'required|integer',
                'province_id' => 'required|numeric|integer|exists:mysql.ln_district,district_id',
                'city_id' => 'required|numeric|integer|exists:mysql.ln_district,district_id',
                'type' => 'required|numeric||in:0,1,2',
                'cate_ids' => 'required|array',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $id = $request->input('id');
        $res = app('repo_black_list');

        $params = $request->only("province_id", "city_id", "type", "cate_ids");
        $city = app('repo_area')->getDistrict($params['city_id']);
        $province = app('repo_area')->getDistrict($params['province_id']);

        $cateIdsArr = $params['cate_ids'];

        $params['cate_ids'] = implode(",", $cateIdsArr);

        $params['area_name'] = $province['name'] . "-" . $city['name'];
        $params['add_time'] = time();
        $params['add_date_time'] = date("Y-m-d H:i:s");

        $rows = $res->saveRule(["id" => $id], $params);
        if (!$rows) {
            throw new BasicException(10001, "更新失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {get} /system-set/black-list/rule 黑名单规则列表
     * @apiVersion 0.1.0
     * @apiName 系统设置-黑名单规则列表
     * @apiGroup 系统设置
     *
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     *
     *
     * @apiSuccessExample 成功响应
     *
     *
    {
    "code": 200,
    "data": {
        "list": [
            {
                "id": 19,
                "cate_ids(黑名单类别)": "6",
                "province_id(省份id)": 370000,
                "city_id(城市id)": 370100,
                "area_name(地区)": "山东-济南",
                "type(受限类型 0 全部   1 ip受限   2 归属地受限)": 0
            }
        ],
        "meta": {
                "page": 1,
                "limit": 10,
                "next": null,
                "total": 1
            }
        },
        "header": {
            "type_list(黑名单类别列表)": [
                    3,
                    4,
                    5,
                    6,
                    111
                ]
            }
        }
     *
     *
     */
    public function list(Request $request) {
        //参数校验
        try {
            $this->validate($request, [
                'perPage' => 'filled|numeric',
                'page' => 'filled|numeric',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $list = app('repo_black_list')->getRuleQueryList($request->input());

        $ext = [
            'type_list' => app('repo_black_list')->getTypeList()
        ];

        return Response::sendList($list, [], $ext);
    }


}
